package com.yanx.framework.advice;

import com.yanx.common.exception.BaseException;
import com.yanx.common.result.IResult;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Order(0)
@ControllerAdvice
public class ExceptionResponseBodyAdvice extends BaseResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.getGenericParameterType().getTypeName().equals(BaseException.class.getTypeName());
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        IResult result = createApiResult(returnType);
        BaseException ex = (BaseException) body;
        result.init(ex.getCode(), ex.getMessage());
        //设置返回状态
        HttpStatus httpStatus = HttpStatus.resolve(ex.getCode());
        if (httpStatus == null) {
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        } else {
            response.setStatusCode(httpStatus);
        }
        return result;
    }

}
